﻿/*----------------------------------------------------------------
// 公司名称：公司名称
// 
// 产品名称：Gaf
//
// 创 建 人：netcasewqs
// 创建日期：2022/3/4
// 邮    箱：netcasewqs@qq.com
//
// Copyright (C) 2022 Gaf，保留所有权利。
//
//----------------------------------------------------------------*/


namespace Gaf.Impl;

internal class AddinRepository
{
    internal List<AddinActivator> addinActivatorsByInstallOrder;
    internal Dictionary<Assembly, string> assemblyLocations = new();
    internal Dictionary<string, string> addinLocations = new(StringComparer.OrdinalIgnoreCase);

    private readonly object syncObj;

    public AddinRepository()
    {
        addinActivatorsByInstallOrder = new List<AddinActivator>();
        syncObj = new object();
    }

    public IEnumerable<AddinActivator> Activators
    {
        get
        {
            lock (syncObj)
            {
                return addinActivatorsByInstallOrder.ToList<AddinActivator>();
            }
        }

    }


    public void Register(AddinActivator activator)
    {
        lock (syncObj)
        {
            activator.Addin.State = AddinState.Installed;
            addinActivatorsByInstallOrder.Add(activator);
            addinLocations[activator.Addin.Name] = activator.Addin.Location;
            foreach (var asm in activator.Addin.Assemblies)
            {
                assemblyLocations[asm] = activator.Addin.Location;
            }
        }
    }

    public void Clear()
    {
        lock (syncObj)
        {
            foreach (var item in addinActivatorsByInstallOrder.OfType<IDisposable>())
            {
                try
                {
                    item.Dispose();
                }
                catch { }
            }
            addinActivatorsByInstallOrder.Clear();
        }
    }

    public int Count
    {
        get
        {
            lock (syncObj)
            {
                return addinActivatorsByInstallOrder.Count;
            }
        }
    }
}
